package com.logos.servlet.req;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@WebServlet("/req3")
public class RequestTest03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        System.out.println("解决乱码前：username = " + username);
        // 乱码原因：tomcat服务器默认使用ISO-8859-1编码，而不是UTF-8编码
        // 解决方案：使用String类的getBytes方法，将ISO-8859-1编码的字符串转换为字节数组，再使用字节数组构造一个新的字符串
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println("解决乱码后：username = " + username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // POST请求逻辑
        this.doGet(req, resp);
    }
}
